//
//  DownLoadCityViewController.m
//  Bus_iPhone
//
//  Created by 修勇 黄 on 12-7-21.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DownLoadCityViewController.h"
#import "BusSetting.h"
#import "BusDataManager.h"
#import "SBJson.h"
#import "MBProgressHUD.h"
#import "BusDataCell.h"

@interface DownLoadCityViewController ()

@end

@implementation DownLoadCityViewController

@synthesize list=_list;
@synthesize viewDidApearRequest=_viewDidApearRequest;

-(void)dealloc{

    [cityOpe release];
    [[[BusSetting defaultSetting]webService]setDelegate:nil];
    [cityRequest clearDelegatesAndCancel];
    [currentIndexPath release];
    [isDownLoadArray release];
    [_list release];
    [super dealloc];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        self.viewDidApearRequest=YES;
        NSString *path=[[NSBundle mainBundle]pathForResource:@"citys" ofType:@"db"];
        cityOpe=[[XXSQLiteOpe alloc]initWithFilePath:path];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setCustomNavigationReturnItem];
    [[[BusSetting defaultSetting]webService]setDelegate:self];
    isDownLoadArray=nil;
    currentIndexPath=nil;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
    
    if (self.viewDidApearRequest) {
        NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:@"getCityDataBaseList",@"action", nil];
        cityRequest=[[[BusSetting defaultSetting]webService ]postRequestWithDic:dic];
        if (!cityRequest) {
            [self showAlertWithTitle:@"提示" msg:@"请求失败，请检查一下您的网络"];
        }else {
            cityRequest.delegate=self;
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [cityRequest startAsynchronous];
        }
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [_list count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [isDownLoadArray release];
    isDownLoadArray=[[[BusSetting defaultSetting]getDownLoadDataList] retain];
    
    static NSString *CellIdentifier = @"Cell";
    BusDataCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell) {
        cell=[[[BusDataCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        [cell.downBtn addTarget:self action:@selector(donwBusFile:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    NSDictionary *dic=[_list objectAtIndex:indexPath.row];
    NSString  *cityName=[dic objectForKey:@"cityName"];
  
    NSString *tempFileName=[NSString stringWithFormat:@"%@.db",cityName];
    cell.state=BusDataFileNoDwonLoad;
    
    if ([isDownLoadArray containsObject:tempFileName]) {
        cell.state=BusDataFileIsDownLoad;
        [[[BusSetting defaultSetting]webService]addProgressDelegate:cell.progressView name:cityName];
    }
    
    if ([[[BusDataManager currentBusDataManager]cityName]isEqualToString:cityName]) {
        cell.state=BusDataFileIsCurrentSet;
    }
      
    cell.textLabel.text=cityName;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [currentIndexPath release];
    currentIndexPath=[indexPath retain];
    NSDictionary *dic=[_list objectAtIndex:indexPath.row];
   // NSLog(@"dic %@",dic);
    BusDataCell *cell=(BusDataCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (cell.state==BusDataFileIsDownLoad) {
        NSString *msg=[NSString stringWithFormat:@"确定设置 %@ 为当前数据库?",[dic objectForKey:@"CityName"]];
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        [alert release];
    }
}
-(void)donwBusFile:(UIButton *)btn{

    BusDataCell *cell=(BusDataCell *)[[btn superview]superview];
    NSIndexPath *indexPath=[self.tableView indexPathForCell:cell];
    NSDictionary *dic=[self.list objectAtIndex:indexPath.row];
    [[[BusSetting defaultSetting]webService]addDwonLoadFileWithHost:[dic objectForKey:@"URL"] fileName:[dic objectForKey:@"CityName"] progress:cell.progressView];
    cell.state=BusDataFileIsDoanLoading;
    
}


#pragma mark -

-(void)busFileDownFailed:(ASIHTTPRequest *)downRequest error:(NSError *)error{

    NSDictionary *dic=[downRequest userInfo];
    NSString *msg=[NSString stringWithFormat:@"%@ 数据库下载失败!",[dic objectForKey:@"name"]];
    [self showAlertWithTitle:@"失败" msg:msg];
    [self.tableView reloadData];
}

-(void)busFileDownSuccess:(ASIHTTPRequest *)downRequest{

    [self.tableView reloadData];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/



#pragma mark -UIAlertViewDelegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex==1) {
        NSDictionary *dic=[_list objectAtIndex:currentIndexPath.row];
        NSString *fileName=[NSString stringWithFormat:@"%@.db",[dic objectForKey:@"CityName"]];
        [[BusSetting defaultSetting]setBusDataFilePathByFileName:fileName];
        [self.tableView reloadData];
    }
}
#pragma mark -ASIHTTPRequestDelegate

-(void)requestFailed:(ASIHTTPRequest *)request{

//     NSLog(@"string %@",request.responseString);
    cityRequest=nil;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    //NSLog(@"error %@",request.error);
    [self.tableView reloadData];
    
}

-(void)requestFinished:(ASIHTTPRequest *)request{

//     NSLog(@"string %@",request.responseString);
    cityRequest=nil;
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
   // NSLog(@"rquest %@",request.responseString);
    NSString *json=[request responseString];
    NSDictionary *dic=nil;
    if ([self isIos5Later]) {
        dic=[NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    }else {
        dic=[json JSONValue];
    }
    if (dic) {
        if ([[dic objectForKey:@"result"] isEqualToString:@"0"]) {
            [self showAlertWithTitle:@"失败" msg:[dic objectForKey:@"reason"]];
        }else{
        
            self.list=[dic objectForKey:@"data"];
            [self.tableView reloadData];
        }
    }else {
        [self showAlertWithTitle:@"提示" msg:@"请求失败"];
    }
}
@end
